import { useCallback, useEffect } from 'react';
import { Tabs, Menu, Dropdown } from 'antd';
import { useNavigate, useLocation, Link } from 'react-router-dom';
import TagsViewAction from './tagViewAction';
import { useDispatch, useSelector } from 'react-redux';
import { addTag, removeTag, removeOtherTag, removeAllTag, setActiveTag } from '@/store/modular/tagsView';
import { getFirstPathCode } from '@/utils/getFirstPathCode';
import {treeToArray} from "@/utils/utils";

const { TabPane } = Tabs;

const TagsView = () => {
	const { tags, activeTagId } = useSelector(state => state.tagsView);
	const { menuList } = useSelector(state => state.user);
	const dispatch = useDispatch();
	const navigate = useNavigate();
	const {pathname} = useLocation();

	//点击tab标签
	const onChange = (key) => {
		const tag = tags.find(tag => tag.path === key);
		if (tag) {
			setCurrentTag(tag.path);
			navigate(tag.path);
		}
	};

	//关闭tab标签
	const onClose = (targetKey) => {
		dispatch(removeTag(targetKey));
	};

	const setCurrentTag = useCallback((id) => {
		const tag = tags.find(item => {
			if (id) {
				return item.path === id;
			} else {
				return item.path === pathname;
			}
		});

		if (tag) {
			dispatch(setActiveTag(tag.path));
			//console.log("=====etag=====",tag)
		}
    },[dispatch, pathname, tags]);

	useEffect(() => {
		const routes = treeToArray(menuList)
		console.log("=====routes=======",routes)
		//console.log("=====pathname=======",pathname)
		if (routes.length) {
			const menu = routes.find(m => m.path === pathname);
			console.log("===menu===",menu)
			let obj = {
				path: menu.path,
				key: menu.key,
				meta: menu.meta,
			}
			if (menu) {
				dispatch(
					addTag({...obj,closable: true,}),
				);
			}
		}
	}, [dispatch, pathname]);

	return (
		<div id="pageTabs" style={{ padding: '0px 0px 6px', }}>
			<Dropdown trigger={['contextMenu']}
				overlay={
					<Menu>
						<Menu.Item key="0" onClick={() => dispatch(removeTag(activeTagId))}>
							关闭当前页面
						</Menu.Item>
						<Menu.Item key="1" onClick={() => dispatch(removeOtherTag())}>
							关闭其它页面
						</Menu.Item>
						<Menu.Item key="2" onClick={() => dispatch(removeAllTag())}>
							关闭所有页面
						</Menu.Item>
						<Menu.Divider />
						<Menu.Item key="3" onClick={() => dispatch(removeAllTag())}>
							关闭所有页面
						</Menu.Item>
					</Menu>
				}
			>
				<Tabs
					tabBarStyle={{ margin: 0 }}
					onChange={onChange}
					activeKey={activeTagId}
					type="editable-card"
					hideAdd
					onEdit={(targetKey, action) => action === 'remove' && onClose(targetKey)}
					tabBarExtraContent={<TagsViewAction />}
				>
					{tags.map(tag => (
						<TabPane tab={tag.meta.title} key={tag.path} closable={tag.closable} />
					))}
				</Tabs>
			</Dropdown>
		</div>
	);
};

export default TagsView;
